package com.example.textroom.data.dao;

import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;

import com.example.textroom.bead.UserTo;

import java.util.List;

/**
 * Description:
 * Author: dengpao
 * Date: 2025/4/29 15:35
 */
@Dao
public interface UserDao {
    @Query("SELECT * FROM user_table")
    List<UserTo> getAll();

    @Query("SELECT * FROM user_table WHERE id = :userId")
    UserTo getUserById(int userId);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertUser(UserTo userTo);

    @Insert
    void insertAll(List<UserTo> userTo);

    @Update
    void updateUser(UserTo userTo);

    @Delete
    void deleteUser(UserTo userTo);

    @Query("DELETE FROM user_table")
    void deleteAll();
//
//    // 使用LiveData观察数据变化
//    @Query("SELECT * FROM USER")
//    LiveData<List<UserTo>> getAllLiveUsers();

    /**
     * 多条件查询用户
     * @param gender 性别(M/F)，null表示不限制性别
     * @param nameKeyword 姓名关键词，null或空表示不限制姓名
     * @param startDate 开始日期，null表示不限制
     * @param endDate 结束日期，null表示不限制
     * @return 符合条件的用户列表，按注册时间降序排列
     */
    @Query("SELECT * FROM user_table WHERE " +
            "(:gender = -1 OR gender = :gender) AND " +
            "(:nameKeyword IS NULL OR user_name LIKE '%' || :nameKeyword || '%') AND " +
            "(:startDate IS NULL OR register_date >= :startDate) AND " +
            "(:endDate IS NULL OR register_date <= :endDate) " +
            "ORDER BY register_date DESC")
    LiveData<List<UserTo>> searchUsers(
            @Nullable int gender,
            @Nullable String nameKeyword,
            @Nullable Long startDate,
            @Nullable Long endDate
    );
//
    // 同步版本
    @Query("SELECT * FROM user_table WHERE " +
            "(:gender =-1 OR gender = :gender) AND " +
            "(:nameKeyword IS NULL OR user_name LIKE '%' || :nameKeyword || '%') AND " +
            "(:startDate IS NULL OR register_date >= :startDate) AND " +
            "(:endDate IS NULL OR register_date <= :endDate) " +
            "ORDER BY register_date DESC")
    List<UserTo> searchUsersSync(
            @Nullable int gender,
            @Nullable String nameKeyword,
            @Nullable Long startDate,
            @Nullable Long endDate
    );

}
